package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.util.RequirePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    // 处理查询所有部门请求
    @RequestMapping("/list")
    @RequirePermission(name="部门页面",expression="department:list")
    public String list(Model model, QueryObject qo) {
        model.addAttribute("pageResult", departmentService.query(qo));
        return "department/list"; // 找视图 /WEB-INF/views/department/list.jsp
    }

    // 新增或修改
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Department department) {
        if (department.getId() == null) { // 新增
            departmentService.save(department);
        } else {
            departmentService.update(department); // 修改
        }
        return "redirect:/department/list.do"; // 让浏览器重新发一次请求
    }

    // 处理删除请求
    @RequestMapping("/delete")
    @ResponseBody
    @RequirePermission(name="部门删除",expression="department:delete")
    //前段方式重定向
    public JsonResult delete(Long id) {

        try {
            if (id != null) {
                departmentService.delete(id);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"系统异常,请联系管理员"); // 让浏览器重新发一次请求
        }
    }

    // 去新增或去修改页面
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        if (id != null) { // 表示去修改
            Department department = departmentService.get(id);
            model.addAttribute("department", department);
        }
        return "department/input"; // 让浏览器重新发一次请求
    }
}
